package com.example.pt.controller;

import com.example.pt.entity.TorrentSeedStats;
import com.example.pt.service.TorrentSeedStatsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import com.example.pt.dto.TorrentSeedInfoDTO;

@RestController
@RequestMapping("/api/torrent")
@CrossOrigin(origins = "*")
public class TorrentSeedStatsController {

    private static final Logger logger = LoggerFactory.getLogger(TorrentSeedStatsController.class);
    
    @Autowired
    private TorrentSeedStatsService torrentSeedStatsService;
    
    /**
     * 接收和处理来自Tracker的种子做种统计信息
     */
    @PostMapping("/stats/update")
    public ResponseEntity<Map<String, Object>> updateSeedStats(@RequestBody Map<String, Object> statsData) {
        Map<String, Object> response = new HashMap<>();
        try {
            String infoHash = (String) statsData.get("infoHash");
            Integer seeders = ((Number) statsData.get("seeders")).intValue();
            Integer leechers = ((Number) statsData.get("leechers")).intValue();
            Integer completed = ((Number) statsData.get("completed")).intValue();
            
            logger.info("收到做种统计：种子Hash={}, 做种={}, 下载中={}, 完成={}",
                    infoHash, seeders, leechers, completed);
            
            boolean result = torrentSeedStatsService.updateSeedStats(infoHash, seeders, leechers, completed);
            
            if (result) {
                response.put("success", true);
                response.put("message", "统计信息更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "统计信息更新失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            logger.error("处理做种统计异常", e);
            response.put("success", false);
            response.put("message", "处理异常：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取指定种子的做种统计信息
     */
    @GetMapping("/stats/{infoHash}")
    public ResponseEntity<Map<String, Object>> getSeedStats(@PathVariable String infoHash) {
        Map<String, Object> response = new HashMap<>();
        try {
            TorrentSeedStats stats = torrentSeedStatsService.getStatsByInfoHash(infoHash);
            if (stats != null) {
                response.put("success", true);
                response.put("data", stats);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "没有找到指定种子的统计信息");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            logger.error("获取做种统计异常", e);
            response.put("success", false);
            response.put("message", "处理异常：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取指定种子的做种和下载人数
     */
    @GetMapping("/stats/count/{infoHash}")
    public ResponseEntity<Map<String, Object>> getSeedCount(@PathVariable String infoHash) {
        Map<String, Object> response = new HashMap<>();
        try {
            TorrentSeedStats stats = torrentSeedStatsService.getStatsByInfoHash(infoHash);
            Map<String, Integer> counts = new HashMap<>();
            
            if (stats != null) {
                counts.put("seeders", stats.getSeeders());
                counts.put("leechers", stats.getLeechers());
                counts.put("completed", stats.getCompleted());
            } else {
                counts.put("seeders", 0);
                counts.put("leechers", 0);
                counts.put("completed", 0);
            }
            
            response.put("success", true);
            response.put("data", counts);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取做种统计异常", e);
            response.put("success", false);
            response.put("message", "处理异常：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 根据种子ID查询做种信息
     * @param tid 种子ID
     * @return 种子做种信息
     */
    @GetMapping("/{tid}/seed-info")
    public ResponseEntity<TorrentSeedInfoDTO> getTorrentSeedInfo(@PathVariable("tid") Integer tid) {
        TorrentSeedInfoDTO seedInfo = torrentSeedStatsService.getTorrentSeedInfoByTid(tid);
        if (seedInfo == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(seedInfo);
    }
} 